package org.xtwy.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class SocketChannelDemo {
    public static void startClient() throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 8999));
		socketChannel.configureBlocking(true);//阻塞才能看出效果

        //创建ByteBuffer
        ByteBuffer buf = ByteBuffer.wrap("hello 夜行侠老师".getBytes("UTF-8"));
        socketChannel.write(buf);

        ByteBuffer byteBuffer = ByteBuffer.allocate(48);
        //如果配置非阻塞，会直接往下运行，不会阻塞
        int size = socketChannel.read(byteBuffer);
        while (size > 0) {
            byteBuffer.flip();
            Charset charset = Charset.forName("UTF-8");
            System.out.println(charset.newDecoder().decode(byteBuffer));
            byteBuffer.clear();
            size = socketChannel.read(byteBuffer);
        }
        buf.clear();
        byteBuffer.clear();
        socketChannel.close();
       //Thread.sleep(50000);
    }

    public static void main(String[] args) throws Exception {
        startClient();
    }
}
